﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.UserData;
using Microsoft.Devices.Sensors;
using Microsoft.Phone.Notification;
using System.Windows.Navigation;
using Microsoft.Xna.Framework;
using Microsoft.Devices;


namespace GestureTest
{
    public partial class GestureMainPage : PhoneApplicationPage
    {
       
        PhoneCallTask phoneTask = new PhoneCallTask();
        SmsComposeTask smsComposeTask = new SmsComposeTask();
        PhoneNumberChooserTask phoneNumberChooserTask = new PhoneNumberChooserTask();
        public static Accelerometer accelerometer { get; set; }

        long previousTimeStamp = 0;
       
        private string gesture { get; set; }

        public ContactData gestureData_i { get; set; }

        public GestureMainPage()
        {
            InitializeComponent();

            InitializeSettings();

            (Application.Current as App).RootFrame.Obscured += OnObscured;
            (Application.Current as App).RootFrame.Unobscured += OnUnobscured;

            phoneNumberChooserTask.Completed += new EventHandler<PhoneNumberResult>(phoneNumberChooserTask_Completed);

        }
        void OnObscured(object sender, ObscuredEventArgs e)
        {
            //Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.Active = false;
            accelerometer.Stop();
         
        }

        void OnUnobscured(object sender, EventArgs e)
        {
            accelerometer.Start();
            // Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.Active = true;
          
        }
        void startAccelerometer()
        {
            if (accelerometer == null)
            {
                // Instantiate the Accelerometer.
                accelerometer = new Accelerometer();
                //time between updates
                //    accelerometer.TimeBetweenUpdates = TimeSpan.FromSeconds(2);
                accelerometer.CurrentValueChanged +=
                    new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accelerometer_CurrentValueChanged);

                try
                {

                    accelerometer.Start();
                    System.Diagnostics.Debug.WriteLine("Accelerometer started");
                }
                catch (InvalidOperationException ex)
                {

                }
            }
            else
                accelerometer.Start();
        }
  
        void accelerometer_CurrentValueChanged(object sender,
 SensorReadingEventArgs<AccelerometerReading> e)
        {

            Dispatcher.BeginInvoke(() => UpdateUI2(e.SensorReading));

                         
        }

        void UpdateUI2(AccelerometerReading e)
        {
            var uri = NavigationService.CurrentSource;
            String uriString = uri.ToString();
           
            // Call UpdateUI on the UI thread and pass the AccelerometerReading.
            if (uriString.Contains("/GestureMainPage.xaml"))
            {
                //  Vector3 acceleration = e.AverageAcceleration.;
                System.Diagnostics.Debug.WriteLine("Acceleration X value" + e.Acceleration.X);
                System.Diagnostics.Debug.WriteLine("Acceleration Y value" + e.Acceleration.Y);
                System.Diagnostics.Debug.WriteLine("Acceleration Z value" + e.Acceleration.Z);

                MoveGesture accelerationRead = new MoveGesture(e.Acceleration
                    );

                string recordGesture = "";


                if (
                    accelerationRead.isLeftTilt())
                {
                    recordGesture = ContactData.LeftGesture;
                  
                    
                }
                else if (accelerationRead.isRightTilt())
                {

                    recordGesture = ContactData.RightGesture;
                  
                }
                else if (accelerationRead.isDownTilt())
                {
                    recordGesture = ContactData.DownGesture;
                  
                   
                }
                else if ( accelerationRead.isUpTilt())
                {
                    recordGesture = ContactData.UpGesture;
                    
                   
                }
            

                gesture = recordGesture;

                
                System.Diagnostics.Debug.WriteLine("Recorded gesture::--" + gesture);
                if (!String.IsNullOrEmpty(gesture))
                {
                    performAction(gesture);
                }
                
            }

        }
        
        void phoneNumberChooserTask_Completed(object sender, PhoneNumberResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {

                String displayName = e.DisplayName; 
                System.Diagnostics.Debug.WriteLine("Name: " + e.DisplayName);
                String number = "" + e.PhoneNumber;
                System.Diagnostics.Debug.WriteLine("Phone Number: " + e.PhoneNumber);


                Navigate(displayName,number);
              
            }

           
        }

        private void vibrateFeedback(){
                VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));

        }
      
        
    
        private long getTimeMiliseconds()
        {
            return DateTime.Now.Ticks / 10000;
        }

       

        private void performAction(string gesture)
        {
            long previousTS = previousTimeStamp;
            long nowTimeStamp = getTimeMiliseconds();
            
            previousTimeStamp = nowTimeStamp;

           if (nowTimeStamp - previousTS < 500)
            {
                return;
            }



            if (GesContactsDB.getInstance().getSize() > 0 && GesContactsDB.getInstance().getContactData(gesture)!=null )
            {
                vibrateFeedback();
               accelerometer.Stop();
                // Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.Active = false;

                ContactData gestureData = GesContactsDB.getInstance().getContactData(gesture);

                if (gestureData == null)
                {
                    return;
                }

                if (gestureData.settings.connectSetting == ContactSettings.CallContact)
                {
                    phoneTask.DisplayName = gestureData.DisplayName;
                    phoneTask.PhoneNumber = gestureData.Number;
                    phoneTask.Show();                  
                
                }
                else if (gestureData.settings.connectSetting == ContactSettings.WriteMessage)
                {
                    smsComposeTask.To = gestureData.DisplayName + "<" + gestureData.Number + ">"; // Mention here the phone number to whom the sms is to be sent
                    smsComposeTask.Body = ""; // the string containing the sms body
                    smsComposeTask.Show();
                }
                else if (gestureData.settings.connectSetting == ContactSettings.SendDistressMessage)
                {
                    smsComposeTask.To = gestureData.DisplayName + "<" + gestureData.Number + ">"; // Mention here the phone number to whom the sms is to be sent
                    smsComposeTask.Body = "I need help"; // the string containing the sms body
                    smsComposeTask.Show();
    

                }

            }


        }
        

        void Navigate(String displayName, String number)
        {
            accelerometer.Stop();
  
            Dispatcher.BeginInvoke(() =>
            {
                NavigationService.Navigate(new Uri("/AddGesturePage.xaml?Name=" + displayName + "&Number=" + number, UriKind.Relative));
            });
           
        }

        
        private void InitializeSettings()
        {

            GesContactsDB.getInstance().load();
            this.listBox.ItemsSource = GesContactsDB.getInstance().getContactsList();
            
        }

        

        private void saveData()
        {
        
            GesContactsDB.getInstance().save();

        }

        




                 

     
     
        private void create_click(object sender, RoutedEventArgs e)
        {

           
            phoneNumberChooserTask.Show();

            
        }

        private void GestureMainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
         
            startAccelerometer();
            this.listBox.ItemsSource = GesContactsDB.getInstance().getContactsList();

            
         
        }

        private void deletegesture_click(object sender, RoutedEventArgs e)
        {
            try
            {
                // int selectedIndex = YourListBoxItemCollection.IndexOf((sender as MenuItem).DataContext)
                ListBoxItem contextMenuListItem = this.listBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;


                ContactData gestureData = (ContactData)contextMenuListItem.DataContext;



                GesContactsDB.getInstance().remove(gestureData.Gesture);
                GesContactsDB.getInstance().save();

                this.listBox.ItemsSource = GesContactsDB.getInstance().getContactsList();


            }
            catch (NullReferenceException exception)
            {
                System.Diagnostics.Debug.WriteLine(exception.Message);
            }
        }

 

        private void editgesture_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                ListBoxItem contextMenuListItem = this.listBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;


                ContactData gestureData_l = (ContactData)contextMenuListItem.DataContext;

                NavigationService.Navigate(new Uri("/AddGesturePage.xaml?Name=" + gestureData_l.DisplayName + "&Number=" + gestureData_l.Number + "&Gesture="+gestureData_l.Gesture, UriKind.Relative));
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {

        }

        private void barSettings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private void barAdd_Click(object sender, EventArgs e)
        {
            phoneNumberChooserTask.Show();
        }

        private void MenuButton_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void contactsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object item = ((ListBox)sender).SelectedItem;
            //object value = ((ListBox)sender).SelectedValue;
            ContactData contactData;

            if (item is ContactData)
            {
                contactData = ((ContactData)item);
                NavigationService.Navigate(new Uri("/settings.xaml?Gesture="+contactData.Gesture+"&Name=" + contactData.DisplayName, UriKind.Relative));
            }
            
            
        }


    }
    /*        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // NavigationEventArgs returns destination page "DestinationPage"
            AddGesturePage addPage = e.Content as AddGesturePage;
            if (addPage != null)
            {
                // Change property of destination page 
               // addPage.accelerometer = accelerometer;
            }

        }
       void startAccelerometerHelper()
        {
          

            if (!Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.Active)
            {
               // Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.ReadingChanged -= Accelerometer_ReadingChanged;
                Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.ReadingChanged += Accelerometer_ReadingChanged;
                Microsoft.Phone.Applications.Common.AccelerometerHelper.Instance.Active = true;
            }
           
        }*/
}